<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Controller\user;

use App\Dao\IntegralDetailDao;
use App\Job\OrderTimeOutJob;
use App\Kernel\Util\UserJwtInstance;
use App\Middleware\User\UserMiddleware;
use App\Request\User\Order\BuyRequest;
use App\Request\User\Order\PayRequest;
use App\Request\User\Order\OrderRequest;
use App\Service\User\IntegralDetailService;
use App\Service\User\OrderService;
use App\Service\User\PaymentService;

use App\Service\User\PingPpService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;

/**
 * 订单服务
 *
 * @AutoController()
 * @Middleware(UserMiddleware::class)
 * @author 张昊(2396675557@qq.com)
 * @package App\Controller\user
 */
class OrderController extends Controller
{
    /**
     * @Inject()
     * @var OrderService
     */
    private $service;

    /**
     * @Inject
     * @var PaymentService
     */
    private $paymentService;

    /**
     * 下单接口
     *
     * @author 刘兴永(aile8880@qq.com)
     * @date 2020-02-28 19:57:00
     * @param BuyRequest $request
     */
    public function buy(BuyRequest $request)
    {
        $params = $request->all();

        $user = UserJwtInstance::instance()->build()->getUser();

        $params['addr_id'] = (int)$params['addr_id'];
        $params['sku_id'] = (int)$params['sku_id'];
        $params['num'] = (int)$params['num'];
        $params['remark'] = isset($params['remark']) ? $params['remark'] : '';
        if (!is_array($params)) $this->error();

        if( !empty($user->safe_pwd) ) {
            //验证安全密码
            if( !password_verify( $params['safe_pwd'], $user->safe_pwd ) ) {
                $this->error('ORDER.REGISTER_FAIL');
            }
        } else {
            $this->error('ORDER.REGISTER_EMPTY');
        }

        $result = $this->service->buy($params);

        // 异步队列，超时未支付关闭订单
        $this->driver->push(new OrderTimeOutJob($result['order_no']), 30 * 60);

        $this->success($result);
    }

    /**
     * 未支付积分商城订单重新支付
     */
    public function unpaid()
    {
        $order_id = (int)$this->request->input('order_id', 0);
        $safe_pwd = (string)$this->request->input('safe_pwd', '');
        $channel = (string)$this->request->input('channel', '');
        if ($order_id === 0) $this->error();

        $user = UserJwtInstance::instance()->build()->getUser();
        if( !empty($user->safe_pwd) ) {
            //验证安全密码
            if( !password_verify( $safe_pwd, $user->safe_pwd ) ) {
                $this->error('ORDER.REGISTER_FAIL');
            }
        } else {
            $this->error('ORDER.REGISTER_EMPTY');
        }

        $result = $this->service->unpaid($order_id,$channel);

        $this->success($result);
    }


    /**
     * 订单支付
     *
     * @author 刘兴永(aile8880@qq.com)
     * @date 2020-02-28 19:57:00
     * @param PayRequest $request
     */
    public function pay(PayRequest $request)
    {
        $order_no = (string)$request->input('order_no');
        $channel = (string)$request->input('channel');

        if ($channel === 'wallet') {
            // 钱包支付
            $payment = $this->service->pay($order_no, 2);
        }
        else {
            // 在线支付
            $result = $this->service->pay($order_no);
            $payment = $this->paymentService->buildPay($result, $channel, '订单支付');
        }

        $this->success($payment);
    }

    /**
     * 获取用户订单
     */
    public function get()
    {
        $status = (int)$this->request->input('status', 0);

        // 状态筛选
        $statusList = [
            0 => [],
            1 => ['status' => $this->service->dao::STATUS_UNPAID],
            2 => ['status' => $this->service->dao::STATUS_PAID],
            3 => ['status' => $this->service->dao::STATUS_DELIVERY],
            4 => ['status' => $this->service->dao::STATUS_RECEIVED],
//            4 => ['status' => $this->service->dao::STATUS_IN_REFUND.' and status = '.$this->service->dao::STATUS_REFUND],
        ];

        $map = $statusList[$status] ?? [];

        $result = $this->service->list( $map );

        $this->success($result);
    }

    /**
     * 取消订单
     *
     * @param OrderRequest $request
     */
    public function cancel_order(OrderRequest $request)
    {
        $params = $request->all();
        $firstOrder = $this->service->dao->getFirstOrder($params['order_id']);

        if( in_array($firstOrder['status'], $this->service->dao::CANCEL_ORDER) ) {
            $this->error('ORDER.STATUS_EXCEPTION');
        }

        $map = [
            'id' => $params['order_id'],
        ];
        $data = [
            'status' => $this->service->dao::STATUS_CANCEL,
        ];

        $update = $this->service->dao->update($map, $data);

        $update ? $this->success() : $this->error();
    }

    /**
     * 确定收货
     *
     * @param OrderRequest $request
     */
    public function sure_order(OrderRequest $request)
    {
        $params = $request->all();
        $firstOrder = $this->service->dao->getFirstOrder($params['order_id']);

        if( in_array($firstOrder['status'], $this->service->dao::SURE_ORDER) ) {
            $this->error('ORDER.STATUS_EXCEPTION');
        }

        $data = [
            'status' => $this->service->dao::STATUS_RECEIVED,
        ];
        $map = [
            'id' => $params['order_id']
        ];

        $update = $this->service->dao->update($map, $data);

        $update ? $this->success() : $this->error();
    }

    /**
     * 删除订单
     */
    public function delete()
    {
        $order_id = (int)$this->request->input('order_id', 0);
        if ($order_id === 0) $this->error();

        $this->service->dao->delete($order_id);

        $this->success();
    }

    /**
     * 订单详情
     */
    public function detail()
    {
        $order_id = (int)$this->request->input('id', 0);

        if ($order_id === 0) $this->error();

        $order = $this->service->dao->detail($order_id);

        $this->success($order);
    }

    /**
     * 获得订单快递信息
     */
    public function expressInfo()
    {
        $order_no = $this->request->input('order_no');
        !$order_no && $this->error("请传订单编号");
        $logistic = $this->service->logistics_dao->getLogisticByOrderNo($order_no);
        !$logistic && $this->error("订单不存在");
        $logistic = $logistic->toArray();
        $this->success($logistic);
    }


}